﻿using FlexFlow.Model;
using FlexFlow.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FlexFlow.MVC.Controllers
{
    [Auth(AuthType.API)]
    public class ProcessDefineAPIController : Controller
    {
        /// <summary>
        /// 创建新的流程定义
        /// </summary>
        /// <param name="creator">
        /// 创建者
        /// </param>
        /// <param name="name">
        /// 流程名称
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult Create(string name)
        {
            var user = DefaultComponentSettings.OnlineUserPool.GetLoginedUserInfo(Request);
            string content = "{\"title\":\"" + name + "\",\"nodes\":{},\"lines\":{},\"areas\":{},\"initNum\":1}";
            if (user == null)
            {
                return Json(new OperateResult()
                {
                    ResultCode = 403,
                    Message = "游客无权执行此操作！"
                });
            }
            return Json(ProcessDefineManager.Default.Create(user.UserId, content, name));
        }
    
        /// <summary>
        /// 载入流程定义文件
        /// </summary>
        /// <param name="fileId">
        /// 文件ID
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult Load(Guid fileId)
        {
            return Json(ProcessDefineManager.Default.Load(fileId));
        }
        /// <summary>
        /// 保存流程定义
        /// </summary>
        /// <param name="fileId">
        /// 要保存的流程定义的文件ID
        /// </param>
        /// <param name="content">
        /// 要保存的内容
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult Save(Guid fileId, string content)
        {
            return Json(ProcessDefineManager.Default.Save(fileId,content));
        }
        /// <summary>
        /// 安装流程
        /// </summary>
        /// <param name="fileId">
        /// 流程文件ID
        /// </param>
        /// <returns>
        /// 操作结果
        /// </returns>
        public ActionResult Install(Guid fileId, string name)
        {
            LoginedUserInfo uinfo = DefaultComponentSettings.OnlineUserPool.GetLoginedUserInfo(Request);
            if (uinfo == null)
            {
                return Json(new OperateResult()
                {
                    ResultCode = 403,
                    Message = "游客不允许安装流程！"
                });
            }
            return Json(ProcessDefineManager.Default.InstallProc(uinfo.UserId, fileId, name));
        }
        public ActionResult GetInstalledProcIdByFileId(Guid fileId)
        {
            return Json(ProcessDefineManager.Default.GetInstalledProcIdByFileId(fileId));
        }
    }
}
